package com.daidai.service.order.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daidai.dao.OrderMapper;
import com.daidai.domain.*;
import com.daidai.service.customer.impl.CustomerServiceImpl;
import com.daidai.service.employee.impl.EmployeeServiceImpl;
import com.daidai.service.order.OrderService;
import com.daidai.service.room.impl.RoomServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RoomServiceImpl rService;
    @Autowired
    CustomerServiceImpl cService;
    @Autowired
    OrderMapper oMapper;
    @Autowired
    EmployeeServiceImpl eMapper;
    @Autowired
    RoomServiceImpl rMapper;

    @Override
    public Common createOrder(Map map) {
        try {
            System.out.println(map.toString());
            Order order = new Order();
            // oid
            order.setOid( IdUtil.fastSimpleUUID());
            // status
            order.setStatus(1);
            // 必要的key

            String session1 = map.get("key").toString().substring(4);
            System.out.println(session1);

            // 停掉redis 测试


            Employee employee = (Employee) eMapper.getEmsById(Integer.parseInt(session1)).getData();
//            Employee employee = (Employee) redisTemplate.opsForValue().get(session);
            // eid
            order.setEid(employee.getEid());
            // 原计划 直接前端传入间隔
            Integer daysOrHours = Integer.parseInt(String.valueOf(map.get("daysOrHours"))) ;
            // 现在前端传入截止日期



            Integer rid =Integer.parseInt(String.valueOf(map.get("rid"))) ;
            System.out.println(rid);
            // rid
            order.setRid(rid);
            Room room = rService.getRoomByRid(rid);
            if(room.getStatus()!=0){
                return  Common.error(500,"该房间不可预订");
            }

            // realprice
            Double extraprice = room.getExtraprice();
            RoomType roomtype = room.getRoomtype();
            Double standardprice = roomtype.getStandardprice();



            String cid =String.valueOf(map.get("cid"));
            long l = Long.parseLong(cid);
            //cid
            order.setCid(l);

            Common cus = cService.getCusByParam("cid", l);

            Customer customer = (Customer) cus.getData();
            customer.setIsdel(1);
            double dis= customer.getGrade1().getDiscount();

            Double realprice=(standardprice+extraprice)*dis;

            DecimalFormat df = new DecimalFormat("0.00");
            String format = df.format(realprice);
            double v = Double.parseDouble(format);
            order.setRealprice(v);
            String now = DateUtil.now();
            order.setStarttime(now);

            // date
            if(room.getRtype()==6){
                // 假设 钟点房 时长 最低1h  最高 6h 任意时间入住
                Date dateNow= DateUtil.parse(now);
                DateTime dateTime = DateUtil.offsetHour(dateNow, daysOrHours);
                order.setEndtime(dateTime.toString());
            }else {
                // 假设一次最多14天 一律中午12点前退房
                Date dateNow= DateUtil.parse(now);
                DateTime dateTime = DateUtil.offsetDay(dateNow, daysOrHours);
                Date parse = DateUtil.parse(dateTime.toString("yyyy-MM-dd"));
                DateTime endtime = DateUtil.offsetHour(parse, 12);
                order.setEndtime(endtime.toString());
            }
            //可选操作
            // remark
            Object remark = map.get("remark");
            if(!ObjectUtil.isNull(remark)){
                order.setRemark(remark.toString());
            }
            // cidrest
            Object cidrest = map.get("cidrest");
            if (!ObjectUtil.isNull(cidrest)) {
                order.setCrest((List<Customer>) cidrest);
            }
            System.out.println(order);
            int insert = oMapper.createOrder(order);

            if(insert==1){
                room.setStatus(1);
                rMapper.updateRoom(room);
                cService.updateCus(customer);

                return Common.success("订单创建成功",order);
            }
            return Common.error(500,"出错");
        }
        catch (Exception e){
            return Common.error(500,"出错");
        }
    }

    @Override
    public Common finishOrder(int rid, Long cid) {
        try {
            Common orderByCR = getOrderByCR(rid, cid);
            Order data = (Order) orderByCR.getData();

            // 订单失效
            data.setStatus(0);
            String now = DateUtil.now();
            data.setRealtime(now);

            // 如果退房超时 给出提示 打在订单上
            Date dateNow= DateUtil.parse(now);
            String endtime = data.getEndtime();
            Date dateend= DateUtil.parse(endtime);
            if(dateNow.getTime()>dateend.getTime()){
                Long  overtime=dateNow.getTime()-dateend.getTime();

                long overHours = TimeUnit.MILLISECONDS.toHours(overtime);
                data.setRemark("超时 "+overHours+"小时");
            }
            // 房间
            Room roomByRid = rService.getRoomByRid(data.getRid());
            if(roomByRid.getStatus().equals(0)){
                return Common.error(500,"房间号错误");
            }
            roomByRid.setStatus(0);
            // 顾客
            Common cus = cService.getCusByParam("cid", cid);
            Customer data1 = (Customer) cus.getData();
            data1.setIsdel(0);
            cService.updateCus(data1);
            rService.updateRoom(roomByRid);
            updateOrder(data);
            return Common.success("退房成功",data);
        }
        catch (Exception e){
            return Common.error(500,"系统错误");
        }
    }

    @Override
    public Common getOrderByCR(int rid, Long cid) {
        try {
            Order Order = oMapper.selectOne(new QueryWrapper<Order>().eq("rid", rid).eq("cid", cid));
            if(ObjectUtil.isNull(Order)){
                return Common.error(500,"信息错误");
            }
            return Common.success("查询成功",Order);
        }catch (Exception e){
            return Common.error(500,"查询出错");
        }
    }

    @Override
    public Common updateOrder(Order Order) {
        try {
            oMapper.update(Order,new QueryWrapper<Order>().eq("oid",Order.getOid()));
            return Common.success("修改成功");
        }catch (Exception e){
            return Common.error(500,"修改失败");
        }
    }

    @Override
    public Common getAllOrderByCid(Long cid) {
        try{
            List<Order> cid1 = oMapper.selectList(new QueryWrapper<Order>().eq("cid", cid));
            return Common.success("查询成功",cid1);
        }catch (Exception e){
            System.out.println(e.getMessage());
            return Common.error(500,"查询出错");
        }
    }

    @Override
    public Common getOrderByStatus(Long cid, int status) {
        try{
            List<Order> cid1 = oMapper.selectList(new QueryWrapper<Order>().eq("cid", cid).
                    eq("status",status));
            return Common.success("查询成功",cid1);
        }catch (Exception e){
            System.out.println(e.getMessage());
            return Common.error(500,"查询出错");
        }
    }

    @Override
    public Common getRunOrder(int i) {
        return Common.success("查询成功",oMapper.selectList(new QueryWrapper<Order>().eq("status",i)));
    }
}
